from .config_mgr import ConfigMgr
import pymysql


class MySQL:
    # 在这里配置自己的SQL服务器
    def __init__(self, db_name):
        self.__config = ConfigMgr.get(db_name)
        self.__db = None
        self.db_host = self.__config['db_host']
        self.db_port = self.__config['db_port']
        self.db_user = self.__config['db_user']
        self.db_pass = self.__config['db_pass']
        self.db_database = self.__config['db_database']
        self.db_status = "fail"
        self.__connect()

    def __del__(self):
        if self.__db is not None:
            self.__db.close()

    def __connect(self):
        if self.__db is None:
            try:
                self.__db = pymysql.connect(
                    host=self.db_host,
                    port=self.db_port,
                    user=self.db_user,
                    passwd=self.db_pass,
                    db=self.db_database,
                    charset="utf8"
                )
            except Exception as e:
                print(e)
            self.db_status = "success" if self.__db is not None else "fail"
        return self.__db

    def query(self, _sql):
        cursor = self.__connect().cursor()
        try:
            cursor.execute(_sql)
            data = cursor.fetchall()
            # 提交到数据库执行
            self.__connect().commit()
        except Exception as e:
            print(e)
            # 如果发生错误则回滚
            self.__connect().rollback()
            return []
        return data

    def exec(self, sql):
        cursor = self.__connect().cursor()
        try:
            cursor.execute(sql)
            # 提交到数据库执行
            self.__connect().commit()
        except Exception as e:
            print(e)
            # 如果发生错误则回滚
            self.__connect().rollback()
            return False
        return True

    def exec_many(self, _sql_list):
        cursor = self.__connect().cursor()
        try:
            if len(_sql_list) == 0:
                return True
            for sql in _sql_list:
                cursor.execute(sql)
            self.__connect().commit()
        except Exception as e:
            print(e)
            # 如果发生错误则回滚
            self.__connect().rollback()
            return False
        return True
